<!--销售订单-->
<template>
  <div class="sales-order">
    <div class="page-header">
      <h2>销售订单</h2>
      <div class="header-actions">
        <i class="action-icon icon-hierarchy"></i>
        <i class="action-icon icon-bell"><sup>0</sup></i>
        <i class="action-icon icon-question"></i>
        <i class="action-icon icon-user"></i>
      </div>
    </div>

    <div class="content-area">
      <div class="controls-bar">
<!--        <button class="btn btn-primary" type="button" :disabled="creating" @click="openCreate">{{ creating ? '提交中...' : '新建' }}</button>-->
        <el-button type="primary" @click="openAdd">新建</el-button>

        <div class="filters">
          <div class="filter-item">
            <label>关键词</label>
            <input v-model="query.keyword" type="text" placeholder="请输入关键词">
          </div>
          <div class="filter-item">
            <label>订单状态</label>
            <select v-model="query.orderStatus">
              <option :value="null">全部</option>
              <option :value="0">已发货</option>
              <option :value="1">已完成</option>
              <option :value="2">部分发货</option>
              <option :value="3">待发货</option>
            </select>
          </div>
          <div class="filter-item">
            <label>期望发货时间</label>
            <input v-model="query.expectedDeliveryDate" type="date" placeholder="请选择期望发货时间">
          </div>
        </div>
        <div class="actions">
          <button class="btn btn-search" type="button" @click="fetchPage">搜索</button>
          <button class="btn btn-reset" type="button" @click="resetFilters">重置</button>
        </div>
      </div>

      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th><input type="checkbox" v-model="allSelected"></th>
              <th>销售订单号</th>
              <th>订单状态</th>
              <th>客户名称</th>
              <th>负责销售</th>
              <th>成单时间</th>
              <th>期望发货时间</th>
              <th>订单商品数</th>
              <th>待发货数量</th>
              <th>已发货数量</th>
              <th>订单总额</th>
              <th>应收总额</th>
              <th>已收总额</th>
              <th>待收总额</th>
              <th>已退总额</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(order, index) in orders" :key="index">
              <td><input type="checkbox" v-model="order.selected"></td>
              <td class="order-number">{{ order.orderNo }}</td>
              <td>{{ renderStatus(order.orderStatus) }}</td>
              <td class="customer-name">{{ order.supplierName }}</td>
              <td>{{ order.userName }}</td>
              <td>{{ formatDate(order.orderDate) }}</td>
              <td>{{ formatDate(order.expectedDeliveryDate) }}</td>
              <td>{{ order.productCount }}</td>
              <td>{{ order.pendingDelivery }}</td>
              <td>{{ order.shippedQuantity }}</td>
              <td>{{ formatNumber(order.orderAmount) }}</td>
              <td>{{ formatNumber(order.receivables) }}</td>
              <td>{{ formatNumber(order.amountReceived) }}</td>
              <td>{{ formatNumber(order.amountCollected) }}</td>
              <td>{{ formatNumber(order.refundedTotal) }}</td>
            </tr>
          </tbody>
        </table>
        <div class="table-footer">
           <div class="footer-actions">
                          <input type="checkbox" id="select-all-footer" v-model="allSelected">
             <label for="select-all-footer">全选</label>
             <button class="btn btn-export">导出</button>
           </div>
           <div class="pagination">
             <button @click="prevPage">&lt;</button>
             <button v-for="p in pagesToShow" :key="p" :class="{ active: p === query.pageNum }" @click="changePage(p)">{{ p }}</button>
             <button @click="nextPage">&gt;</button>
             <select v-model.number="query.pageSize" @change="changePageSize">
               <option :value="10">10条/页</option>
               <option :value="20">20条/页</option>
               <option :value="50">50条/页</option>
             </select>
           </div>
        </div>
        <!-- 新增弹窗 -->
        <el-dialog v-model="addOpen" title="新增销售订单" width="640px">
          <div class="form-grid">
            <el-form :model="addForm" label-width="120px">
<!--              <el-form-item label="销售单号">-->
<!--                <el-input v-model="addForm.orderNo" placeholder="XSDD..." />-->
<!--              </el-form-item>-->
              <el-col :span="12">
                <el-form-item label="成单时间" prop="orderDate">
                  <el-date-picker
                      v-model="addForm.orderDate"
                      type="date"
                      placeholder="选择日期"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-form-item label="联系人" prop="uId">
                <el-select v-model="addForm.uId" placeholder="请选择联系人">
                  <el-option v-for="user in users" :key="user.userId" :label="user.username" :value="user.userId"></el-option>
                </el-select>
              </el-form-item>
              <el-col :span="12">
                <el-form-item label="期望发货时间" prop="expectedDeliveryDate">
                  <el-date-picker
                      v-model="addForm.expectedDeliveryDate"
                      type="date"
                      placeholder="选择日期"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-form-item label="订单状态">
                <el-select v-model.number="addForm.orderStatus" style="width:100%">
                  <el-option :value="0" label="已发货" />
                  <el-option :value="1" label="已完成" />
                  <el-option :value="2" label="部分发货" />
                  <el-option :value="3" label="待发货" />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <el-button type="primary" @click="submitAdd">确 定</el-button>
            <el-button @click="addOpen=false">取 消</el-button>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SalesOrder',
  data() {
    return {
      query: { keyword: '', orderStatus: null, expectedDeliveryDate: '', pageNum: 1, pageSize: 10 },
      orders: [],
      total: 0,
      creating: false,
      addOpen: false,
      addForm: {
        orderNo: '',
        orderDate: '',
        userName: '',
        expectedDeliveryDate: '',
        orderStatus: 0,
        uId: null
      },
      users: [],
    }
  },
  created() {
    this.fetchPage()
    this.loadUsers()
  },
  computed: {
    allSelected: {
      get() {
        return this.orders.length > 0 && this.orders.every(item => item.selected);
      },
      set(value) {
        this.orders.forEach(item => {
          item.selected = value;
        });
      }
    },
    maxPage() {
      return Math.max(1, Math.ceil(this.total / (this.query.pageSize || 10)))
    },
    pagesToShow() {
      const pages = []
      const max = this.maxPage
      const cur = this.query.pageNum
      const start = Math.max(1, cur - 2)
      const end = Math.min(max, start + 4)
      for (let i = start; i <= end; i++) pages.push(i)
      return pages
    }
  },
  methods: {
    openAdd(){
      this.addForm = { orderNo:'', orderDate:'', userName:'', expectedDeliveryDate:'', orderStatus:0, uId: null}
      this.addOpen = true
    },
    renderStatus(s) {
      const map = { 0: '已发货', 1: '已完成', 2: '部分发货', 3: '待发货' }
      return map[s] || '-'
    },
    formatDate(v) {
      if (!v) return ''
      const d = new Date(v)
      if (Number.isNaN(d.getTime())) return ''
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    formatNumber(n) {
      if (n === null || n === undefined) return 0
      const num = Number(n)
      if (Number.isNaN(num)) return 0
      return num.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    },
    async fetchPage() {
      const { pageSalesOrders } = await import('@/api/sale/SalesOrders')
      const res = await pageSalesOrders(this.query)
      const payload = res?.data?.data || {}
      this.orders = (payload.records || []).map(it => ({ ...it, selected: false }))
      this.total = Number(payload.total || 0)
      if (payload.current) this.query.pageNum = Number(payload.current)
      if (payload.size) this.query.pageSize = Number(payload.size)
    },
    async openCreate() {
      if (this.creating) return
      this.creating = true
      const { addSalesOrder } = await import('@/api/sale/SalesOrders')
      const payload = {
        orderStatus: 3,
        customerId: 1,
        uId: 2,
        orderDate: new Date(),
        expectedDeliveryDate: new Date(),
        productCount: 0,
        pendingDelivery: 0,
        shippedQuantity: 0
      }
      try {
        const res = await addSalesOrder(payload, { userId: 2 })
        if (res?.data?.code === 200) {
          this.fetchPage()
        } else {
          console.error('新增失败', res)
        }
      } finally {
        this.creating = false
      }
    },
    resetFilters() {
      this.query = { keyword: '', orderStatus: null, expectedDeliveryDate: '', pageNum: 1, pageSize: this.query.pageSize || 10 }
      this.fetchPage()
    },
    changePage(p) {
      if (p === this.query.pageNum) return
      this.query.pageNum = p
      this.fetchPage()
    },
    prevPage() {
      if (this.query.pageNum <= 1) return
      this.query.pageNum -= 1
      this.fetchPage()
    },
    nextPage() {
      const max = this.maxPage
      if (this.query.pageNum >= max) return
      this.query.pageNum += 1
      this.fetchPage()
    },
    changePageSize() {
      this.query.pageNum = 1
      this.fetchPage()
    },
    async submitAdd() {
      // 表单验证
      if (!this.addForm.uId) {
        this.$message.error('请选择联系人')
        return
      }
      if (!this.addForm.orderDate) {
        this.$message.error('请选择成单时间')
        return
      }
      if (!this.addForm.expectedDeliveryDate) {
        this.$message.error('请选择期望发货时间')
        return
      }

      try {
        const { addSalesOrder } = await import('@/api/sale/SalesOrders')

        // 验证日期值
        console.log('表单数据:', this.addForm)
        console.log('成单时间:', this.addForm.orderDate, typeof this.addForm.orderDate)
        console.log('期望发货时间:', this.addForm.expectedDeliveryDate, typeof this.addForm.expectedDeliveryDate)

        // 处理日期值，确保格式正确
        let orderDate = this.addForm.orderDate
        let expectedDeliveryDate = this.addForm.expectedDeliveryDate

        // 如果日期值包含占位符，使用当前日期
        if (orderDate && (orderDate.includes('yyyy') || orderDate.includes('MM') || orderDate.includes('DD'))) {
          orderDate = new Date().toISOString().split('T')[0] // 格式：YYYY-MM-DD
          console.log('成单时间包含占位符，使用当前日期:', orderDate)
        }

        if (expectedDeliveryDate && (expectedDeliveryDate.includes('yyyy') || expectedDeliveryDate.includes('MM') || expectedDeliveryDate.includes('DD'))) {
          expectedDeliveryDate = new Date().toISOString().split('T')[0] // 格式：YYYY-MM-DD
          console.log('期望发货时间包含占位符，使用当前日期:', expectedDeliveryDate)
        }

        // 构建完整的请求数据，使用与openCreate相同的格式
        const payload = {
          orderStatus: this.addForm.orderStatus || 3,
          customerId: 1,
          uId: this.addForm.uId,
          orderDate: orderDate, // 处理后的日期值
          expectedDeliveryDate: expectedDeliveryDate, // 处理后的日期值
          productCount: 0,
          pendingDelivery: 0,
          shippedQuantity: 0
        }
        console.log('提交的数据:', payload)
        const res = await addSalesOrder(payload, { userId: this.addForm.uId })
        if (res?.data?.code === 200) {
          this.$message.success('新增成功')
          this.addOpen = false
          this.fetchPage()
        } else {
          this.$message.error(res?.data?.message || '新增失败')
        }
      } catch (error) {
        console.error('新增失败', error)
        this.$message.error('新增失败: ' + (error.response?.data?.message || error.message))
      }
    },
    async loadUsers() {
      try {
        // 这里需要根据实际的用户API来加载用户数据
        // 暂时使用模拟数据
        this.users = [
          { userId: 1, username: '张三' },
          { userId: 2, username: '李四' },
          { userId: 3, username: '王五' }
        ]
      } catch (error) {
        console.error('加载用户数据失败', error)
      }
    }
  }
}
</script>

<style scoped>
.sales-order { background-color: #f7f8fa; padding: 20px; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.page-header h2 { font-size: 20px; color: #333; }
.header-actions { display: flex; align-items: center; gap: 20px; }
.action-icon { font-size: 18px; color: #666; cursor: pointer; position: relative; }
.icon-bell sup { position: absolute; top: -5px; right: -10px; background: red; color: white; border-radius: 50%; padding: 2px 5px; font-size: 10px; }
.content-area { background: white; padding: 20px; border-radius: 8px; }
.controls-bar { display: flex; flex-wrap: wrap; align-items: center; margin-bottom: 20px; gap: 15px; }
.btn { border: 1px solid #dcdfe6; background: white; padding: 8px 15px; border-radius: 4px; cursor: pointer; }
.btn-primary { background: #409eff; color: white; border-color: #409eff; }
.filters { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; flex-grow: 1; }
.filter-item { display: flex; align-items: center; gap: 10px; }
.filter-item label { color: #666; font-size: 14px; }
.filter-item input, .filter-item select { border: 1px solid #dcdfe6; padding: 8px; border-radius: 4px; }
.actions { display: flex; gap: 10px; }
.btn-search { background: #409eff; color: white; border-color: #409eff; }
.table-container { border: 1px solid #ebeef5; border-radius: 4px; }
.data-table { width: 100%; border-collapse: collapse; }
.data-table th, .data-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #ebeef5; }
.data-table th { background: #fafafa; color: #606266; font-weight: 500; }
.data-table td { color: #606266; }
.order-number, .customer-name { color: #409eff; cursor: pointer; }
.status-pending { color: #e6a23c; }
.status-partial { color: #f56c6c; }
.status-shipped { color: #67c23a; }
.status-completed { color: #909399; }
.table-footer { display: flex; justify-content: space-between; align-items: center; padding: 15px; }
.footer-actions { display: flex; align-items: center; gap: 10px; }
.btn-export { border: 1px solid #dcdfe6; background: white; padding: 8px 15px; border-radius: 4px; cursor: pointer; }
.pagination { display: flex; align-items: center; gap: 5px; }
.pagination button { border: 1px solid #dcdfe6; background: white; padding: 5px 10px; cursor: pointer; }
.pagination button.active { background: #409eff; color: white; border-color: #409eff; }
</style>
